import React, { useState, useEffect, useRef } from 'react';
import { Dialog, Loading } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import html2canvas from 'html2canvas';
import styles from './QR.module.scss';
import { useStore } from '@/hooks';

interface QRProps {
  name: string, // 二维码描述文字
  open: boolean, // 打开关闭modal
  onCancel: () => void, // 关闭modal事件
  describe?: string, // 底部文字描述
  modalStyle?: Object; // modal自定义样式
  baseUrl: string, // url核心链接
  okText?: string, // 自定义确定按钮文字
  cancelText?: string, // 自定义取消按钮文字
  username: string,
}

export default observer(function ({ modal, ...props }: { modal: QRProps }, ...any) {
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const { driverStore: store } = useStore();
  const divRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    setLoading(true);
    if (modal.open) {
      (async () => {
        const baseUrl = await store.getURL(modal.username);
        setUrl(baseUrl);
        setLoading(false);
      })()
    }
  }, [modal]);

  const cancelHandle = () => {
    modal.onCancel();
  };

  const addCompany = () => {
    // 使用 html2canvas 将 div 转换为图片，并下载到本地
    setTimeout(() => {
      if (divRef.current) {
        html2canvas(divRef.current, { useCORS: true }).then((canvas) => {
          const link = document.createElement('a');
          link.href = canvas.toDataURL('image/png');
          link.download = `${modal.name}专属二维码.png`;
          link.click();
          modal.onCancel();
        });
      }
    }, 500);
  };

  return (
    <>
      <Dialog
        v2
        title={`${modal.name}专属二维码`}
        visible={modal.open}
        style={{ width: 500, ...modal.modalStyle }}
        onOk={addCompany}
        okProps={{ children: modal.okText }}
        onClose={cancelHandle}
        cancelProps={{ children: modal.cancelText }}
      >
        <Loading visible={loading} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <div
            // 使用非空断言运算符 ! 来告诉 TypeScript 你确定 ref 不会为 null
            ref={divRef!}
            id="qrcode-container"
            className={styles.qr_container}
          >
            <div
              className={styles.qr_content}
            >
              <img src={url} style={{ width: '70%' }}  alt="这是一个二维码" />
              <div style={{ marginTop: 20 }} className={styles.qr_content_name}>{modal.name}</div>
              <div>{modal?.describe || '三地通跨境出行服务平台'}</div>
            </div>
          </div>
        </Loading>
      </Dialog>
    </>
  );
});
